using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdminDto.CarType.AreaDtos;
using AvalonAdminDto.CarType.BrandDtos;
using AvalonAdminDto.CarType.CountryDtos;
using AvalonAdminDto.Common;
using D.UtilCore.Dtos;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace AvalonAdmin.Pages.CarType.ViewModels.Brand
{
    /// <summary>
    /// 品牌
    /// </summary>
    public class BrandModifyViewModel : BaseModifyViewModel
    {
        #region 页面属性及初始化数据

        private string? _id;
        
        public ObservableCollection<RepArea> AreaList { get; set; }
        public ObservableCollection<RepCountry> CountryList { get; set; }
        
        public BrandModifyViewModel(string? id = null, ViewStatus? viewStatus = ViewStatus.Add) : base()
        {
            _id = id;
            SetupFormStatus(viewStatus);

            // 如果有ID，则加载数据
            if (!string.IsNullOrEmpty(_id))
            {
                _ = Task.Run(async () =>
                {
                    await QueryAreaAsync();
                    await QueryAsync();
                });
            }
        }

        /// <summary>
        /// 查询数据（用于刷新当前品牌数据）
        /// </summary>
        public override async Task<bool> QueryAsync()
        {
            if (!string.IsNullOrEmpty(_id))
            {
                try
                {
                    var res = await HttpHelper<RepBrand>.GetAsync($"{ApiUrl.GetBrand}/{_id}");

                    if (res.Code == StatusCodeEnum.OK && res.Data != null)
                    {
                        _id = res.Data.Id;
                        // 加载关联的地区信息
                        //if (!string.IsNullOrEmpty(res.Data.BelongingPlace))
                        //{
                        //    var resArea = await HttpHelper<RepArea>.GetAsync($"{ApiUrl.GetArea}/{res.Data.BelongingPlace}");
                        //    if (resArea.Code == StatusCodeEnum.OK && resArea.Data != null)
                        //    {
                        //        _repArea = resArea.Data;
                        //        Area = _repArea.Name ?? string.Empty;
                        //    }
                        //}

                        // 加载关联的国家信息
                        //if (!string.IsNullOrEmpty(res.Data.ManufacturingCountry))
                        //{
                        //    var resCountry = await HttpHelper<RepCountry>.GetAsync($"{ApiUrl.GetCountry}/{res.Data.ManufacturingCountry}");
                        //    if (resCountry.Code == StatusCodeEnum.OK && resCountry.Data != null)
                        //    {
                        //        _repCountry = resCountry.Data;
                        //        Country = _repCountry.Name ?? string.Empty;
                        //    }
                        //}
                    }
                    else if (res.Code == StatusCodeEnum.Waring)
                    {
                        ShowWarning(res.Msg);
                    }
                    else
                    {
                        ShowError(res.Msg ?? "加载品牌数据失败");
                    }
                }
                catch (System.Exception ex)
                {
                    ShowError($"加载品牌数据失败：{ex.Message}");
                }
            }
            return true;
        }

        private async Task QueryAreaAsync()
        {
            if (AreaList != null)
            {
                AreaList.Clear();
            }
            else
            {
                AreaList = new ObservableCollection<RepArea>();
            }
            var resArea = await HttpHelper<List<RepArea>>.GetAsync($"{ApiUrl.QueryAreaList}");
            if (resArea.Code == StatusCodeEnum.OK && resArea.Data != null)
            {
                foreach (var res in resArea.Data)
                {
                    AreaList.Add(res);
                }
            }
        }

        private async Task QueryCountryAsync(string areaId)
        {
            if (CountryList != null)
            {
                CountryList.Clear();
            }
            else
            {
                CountryList = new ObservableCollection<RepCountry>();
            }
            var resCountry = await HttpHelper<List<RepCountry>>.GetAsync($"{ApiUrl.QueryCountryList}/{areaId}");
            if (resCountry.Code == StatusCodeEnum.OK && resCountry.Data != null)
            {
                foreach (var res in resCountry.Data)
                {
                    CountryList.Add(res);
                }
            }
        }

        #endregion

        #region 数据编辑属性

        private RepArea _area;
        /// <summary>
        /// 所属地区（显示用）
        /// </summary>
        [Required(ErrorMessage = "所属地区不能为空")]
        public RepArea Area
        {
            get => _area;
            set
            {
                SetProperty(ref _area, value);
                QueryCountryAsync(_area.Id);
            }
        }

        private RepCountry _country;
        /// <summary>
        /// 所属国家（显示用）
        /// </summary>
        [Required(ErrorMessage = "所属国家不能为空")]
        public RepCountry Country
        {
            get => _country;
            set => SetProperty(ref _country, value);
        }

        private string? name;
        /// <summary>
        /// 名称
        /// </summary>
        [Required(ErrorMessage = "名称不能为空")]
        public string? Name
        {
            get => name;
            set => SetProperty(ref name, value);
        }

        private string? code;
        /// <summary>
        /// 编码
        /// </summary>
        [Required(ErrorMessage = "编码不能为空")]
        public string? Code
        {
            get => code;
            set => SetProperty(ref code, value);
        }

        private string? englishName;
        /// <summary>
        /// 英文名
        /// </summary>
        public string? EnglishName
        {
            get => englishName;
            set => SetProperty(ref englishName, value);
        }

        private string? description;
        /// <summary>
        /// 描述
        /// </summary>
        public string? Description
        {
            get => englishName;
            set => SetProperty(ref description, value);
        }
        
        #endregion

        #region 提交，重置

        /// <summary>
        /// 提交表单数据
        /// </summary>
        protected override async Task SubmitAsync()
        {
            try
            {
                // 验证输入参数
                if (!ValidateInput())
                {
                    return;
                }

                if (string.IsNullOrEmpty(_id))
                {
                    // 添加品牌
                    var res = await HttpHelper<int>.PostAsync(ApiUrl.AddBrand, new ReqAddBrand()
                    {
                        BelongingPlace = Area?.Id,
                        ManufacturingCountry = Country?.Id,
                        Name = Name,
                        Code = Code,
                        EnglishName = EnglishName,
                    });

                    HandleApiResponse(res, "添加成功", "添加失败");
                }
                else
                {
                    // 修改品牌
                    var res = await HttpHelper<int>.PutAsync(ApiUrl.UpdateBrand, new ReqUpdateBrand()
                    {
                        Id = _id,
                        Name = Name,
                        Code = Code,
                        EnglishName = EnglishName,
                        BelongingPlace = Area?.Id,
                        ManufacturingCountry = Country?.Id,
                    });

                    HandleApiResponse(res, "修改成功", "修改失败");
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 验证输入参数
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateInput()
        {
            if (string.IsNullOrEmpty(Name))
            {
                ShowWarning("品牌名称不能为空");
                return false;
            }

            if (string.IsNullOrEmpty(Code))
            {
                ShowWarning("品牌编码不能为空");
                return false;
            }

            if (string.IsNullOrEmpty(EnglishName))
            {
                ShowWarning("英文名称不能为空");
                return false;
            }

            if (Area == null)
            {
                ShowWarning("请选择所属地区");
                return false;
            }

            if (Country == null)
            {
                ShowWarning("请选择所属国家");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            Area = null;
            Country = null;
            Name = null;
            Code = null;
            EnglishName = null;
        }

        #endregion
    }
}


